package com.yxinsur.imc.web.controller.business;

import com.yxinsur.imc.business.domain.ApiBrokerOnline;
import com.yxinsur.imc.business.excel.BrokerRelationTemplate;
import com.yxinsur.imc.business.excel.BrokerTemplate;
import com.yxinsur.imc.business.form.BrokerDimissionForm;
import com.yxinsur.imc.business.form.BrokerDimissionSearchForm;
import com.yxinsur.imc.business.form.BrokerSaveForm;
import com.yxinsur.imc.business.form.BrokerSearchForm;
import com.yxinsur.imc.business.service.IImcBrokerRelationService;
import com.yxinsur.imc.business.service.IImcBrokerRoleService;
import com.yxinsur.imc.business.service.IImcBrokerService;
import com.yxinsur.imc.business.vo.BrokerLeaveVo;
import com.yxinsur.imc.business.vo.BrokerVo;
import com.yxinsur.imc.common.annotation.Log;
import com.yxinsur.imc.common.core.controller.BaseController;
import com.yxinsur.imc.common.core.domain.AjaxResult;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.core.domain.model.LoginUser;
import com.yxinsur.imc.common.core.page.TableDataInfo;
import com.yxinsur.imc.common.enums.BusinessType;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.ServletUtils;
import com.yxinsur.imc.common.utils.poi.ExcelUtil;
import com.yxinsur.imc.framework.web.service.TokenService;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 代理人信息Controller
 *
 * @author imc
 * @date 2021-03-18
 */
@Api(value = "代理人服务接口", tags = "代理人服务接口")
@RestController
@RequestMapping("/business/broker")
public class ImcBrokerController extends BaseController {
    @Autowired
    private IImcBrokerService imcBrokerService;
    @Autowired
    private IImcBrokerRelationService imcBrokerRelationService;
    @Autowired
    private IImcBrokerRoleService imcBrokerRoleService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysOrgMapper sysOrgMapper;

    /**
     * 查询代理人信息列表
     */
    //@PreAuthorize("@ss.hasPermi('business:broker:list')")
    @ApiOperation("获取代理人列表")
    @GetMapping("/list")
    public TableDataInfo list(BrokerSearchForm broker) {
        Long orgId = broker.getOrgId();
        if (orgId == null) {
            String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
            String[] split = authOrgIds.split(",");
            List<String> orgStrList = Arrays.asList(split);
            List<Long> collect = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
            broker.setOrgIds(collect);
        } else {
            List<SysOrg> sysOrgs = sysOrgMapper.selectChildrenOrgById(orgId);
            List<Long> orgIds = sysOrgs.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            orgIds.add(orgId);
            broker.setOrgIds(orgIds);
        }
        startPage();
        ArrayList<BrokerVo> brokerVos = imcBrokerService.selectImcBrokerBaseInfo(broker);
        return getDataTable(brokerVos);
    }

    /**
     * 导出代理人信息列表
     */
    //@PreAuthorize("@ss.hasPermi('business:broker:export')")
    @ApiOperation("代理人导出功能")
    @Log(title = "代理人导出功能", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BrokerSearchForm imcBroker) {
        //startPage();
        Long orgId = imcBroker.getOrgId();
        if (orgId == null) {
            String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
            String[] split = authOrgIds.split(",");
            List<String> orgStrList = Arrays.asList(split);
            List<Long> collect = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
            imcBroker.setOrgIds(collect);
        } else {
            List<SysOrg> sysOrgs = sysOrgMapper.selectChildrenOrgById(orgId);
            List<Long> orgIds = sysOrgs.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            orgIds.add(orgId);
            imcBroker.setOrgIds(orgIds);
        }
        ArrayList<BrokerVo> brokerVos = imcBrokerService.selectImcBrokerBaseInfo(imcBroker);
        ExcelUtil<BrokerVo> util = new ExcelUtil<BrokerVo>(BrokerVo.class);
        return util.exportExcel(brokerVos, "人员管理列表数据");
    }

    /**
     * 导入代理人信息列表
     */

    @ApiOperation(value = "代理人模板导出", produces = "application/octet-stream")
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<BrokerTemplate> util = new ExcelUtil<BrokerTemplate>(BrokerTemplate.class);
        return util.importTemplateExcel("代理人数据");
    }

    @Log(title = "代理人信息导入", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "代理人信息导入")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BrokerTemplate> util = new ExcelUtil<BrokerTemplate>(BrokerTemplate.class);
        List<BrokerTemplate> brokerList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        HashMap<String, Object> resultMap = imcBrokerService.checkImportBroker(brokerList);
        if ((boolean) resultMap.get("flag")) {
            String message = imcBrokerService.importBroker(brokerList, updateSupport, operName);
            return AjaxResult.success(message);
        } else {
            return AjaxResult.error((String) resultMap.get("message"));
        }

    }


    /**
     * 导入代理人信息列表
     */

    @ApiOperation(value = "代理人推荐关系模板导出", produces = "application/octet-stream")
    @GetMapping("/importRelationTemplate")
    public AjaxResult importRelationTemplate() {
        ExcelUtil<BrokerRelationTemplate> util = new ExcelUtil<BrokerRelationTemplate>(BrokerRelationTemplate.class);
        return util.importTemplateExcel("代理人推荐关系数据");
    }

    @Log(title = "代理人推荐关系导入", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "代理人推荐关系导入")
    @PostMapping("/importRelationData")
    public AjaxResult importRelationData(MultipartFile file) throws Exception {
        ExcelUtil<BrokerRelationTemplate> util = new ExcelUtil<BrokerRelationTemplate>(BrokerRelationTemplate.class);
        List<BrokerRelationTemplate> brokerRelationList = util.importExcel(file.getInputStream());
        HashMap<String, Object> resultMap = imcBrokerService.checkImportRelation(brokerRelationList);
        if ((boolean) resultMap.get("flag")) {
            String message = imcBrokerService.importRelation(brokerRelationList);
            return AjaxResult.success(message);
        } else {
            return AjaxResult.error((String) resultMap.get("message"));
        }
    }

    /**
     * 获取代理人信息详细信息
     */
    @ApiOperation("获取代理人信息")
//    @PreAuthorize("@ss.hasPermi('business:broker:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(imcBrokerService.selectImcBrokerById(id));
    }

    /**
     * 新增代理人信息
     */
    //@PreAuthorize("@ss.hasPermi('business:broker:add')")
    @ApiOperation("新增代理人")
    @Log(title = "新增代理人", businessType = BusinessType.INSERT)
    @PostMapping("/addBroker")
    public AjaxResult addBroker(@RequestBody BrokerSaveForm broker) {
        try {
            imcBrokerService.insertImcBroker(broker);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @ApiOperation("工号重复校验")
    @PostMapping("/checkBrokerCode/{brokerCode}")
    public AjaxResult checkBrokerCode(@PathVariable("brokerCode") String brokerCode) {
        if (imcBrokerService.checkBrokerCode(brokerCode)) {
            return AjaxResult.success("工号可用");
        }
        return AjaxResult.error("同租户下已存在该工号");
    }

    @ApiOperation("证件号码校验")
    @PostMapping("/checkBrokerCertiCode/{certiCode}")
    public AjaxResult checkBrokerCertiCode(@PathVariable("certiCode") String certiCode) {
        if (imcBrokerService.checkBrokerCertiCode(certiCode)) {
            return AjaxResult.success("证件号所属人员尚未入职");
        }
        return AjaxResult.error("证件号已存在，请检查");
    }

    /**
     * 修改代理人信息
     */
    //@PreAuthorize("@ss.hasPermi('business:broker:edit')")
    @ApiOperation("编辑代理人")
    @Log(title = "编辑代理人", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody BrokerSaveForm broker) {
        try {
            imcBrokerService.updateImcBroker(broker);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    @ApiOperation("锁定代理人信息")
    @Log(title = "锁定代理人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/lockBroker/{id}/{lock}")
    public AjaxResult lockBroker(@PathVariable("id") Long id, @PathVariable("lock") String lock) {
        try {
            imcBrokerService.lockBroker(id, lock);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除代理人信息
     */
    //@PreAuthorize("@ss.hasPermi('business:broker:remove')")
    @ApiOperation("删除代理人信息")
    @Log(title = "删除代理人信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        imcBrokerService.deleteCheck(ids);
        return toAjax(imcBrokerService.deleteImcBrokerByIds(ids));
    }

    @ApiOperation("获取人员所辖")
    @PostMapping("/relation/{brokerId}")
    public TableDataInfo relation(@PathVariable("brokerId") Long brokerId) {
        return getDataTable(imcBrokerRelationService.treeDataWithoutUp(brokerId));
    }


    @ApiOperation("获取人员关系图")
    @PostMapping("/relationDiagram/{brokerId}")
    public AjaxResult relationDiagram(@PathVariable("brokerId") Long brokerId) {
        return AjaxResult.success(imcBrokerRelationService.relationDiagram(brokerId));
    }


    /**
     * 新增离职信息
     */
    //@PreAuthorize("@ss.hasPermi('system:dimission:add')")
    @ApiOperation("新增离职信息")
    @Log(title = "新增离职信息", businessType = BusinessType.UPDATE)
    @PostMapping("/addDimission")
    public AjaxResult addDimission(@RequestBody BrokerDimissionForm brokerForm) {
        return toAjax(imcBrokerService.insertImcBrokerDimission(brokerForm));
    }

    /**
     * 撤销离职人员信息
     */
    //@PreAuthorize("@ss.hasPermi('system:dimission:add')")
    @ApiOperation("撤销离职信息")
    @Log(title = "撤销离职信息", businessType = BusinessType.UPDATE)
    @PostMapping("/cancelDimission/{brokerId}")
    public AjaxResult cancelDimission(@PathVariable("brokerId") Long brokerId) {
        return toAjax(imcBrokerService.cancelDimission(brokerId));
    }


    /**
     * 查询离职代理人列表
     */
    //@PreAuthorize("@ss.hasPermi('system:dimission:list')")
    @ApiOperation("查询离职代理人列表")
    @GetMapping("/dimissionList")
    public TableDataInfo dimissionList(BrokerDimissionSearchForm brokerForm) {
        startPage();
        List<BrokerLeaveVo> list = imcBrokerService.selectImcBrokerDimissionList(brokerForm);
        return getDataTable(list);
    }

    @ApiOperation("获取当前租户下代理人最大工号")
    @GetMapping("/getMaxBrokerCode")
    public AjaxResult getMaxBrokerCode() {
        return AjaxResult.success(imcBrokerService.getMaxBrokerCode());
    }


    /**
     * 查询在线入司代理人选择框数据列表
     */
    @ApiOperation("查询在线入司代理人")
    @ResponseBody
    @PostMapping("/onlineList")
    public TableDataInfo onlineList(String fullName,Long orgId) {
        List<ApiBrokerOnline>  apiBrokerOnlines = imcBrokerService.choiceOnlineList(fullName,orgId);
        return getDataTable(apiBrokerOnlines);
    }


}
